import { Component, OnInit, Input } from '@angular/core';
import { NzModalRef, NzMessageService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { GroupService } from 'src/app/core/service/group.service';
import { UserService } from 'src/app/core/service/user.service';

@Component({
  selector: 'app-add-user',
  templateUrl: './add-user.component.html',
  styleUrls: ['./add-user.component.scss']
})
export class AddUserComponent implements OnInit {
  teamList: any;
  groupList: any;
  roleGroup: any;
  userForm: FormGroup;
  ldapForm: FormGroup;
  passwordForm: FormGroup;
  emailForm: FormGroup;

  info = {};
  defaultValue = '0';

  msgFlag = '';

  constructor(
    private modal: NzModalRef,
    private groupService: GroupService,
    private userService: UserService,
    private nzMessageService: NzMessageService,
    fb: FormBuilder
  ) {
    this.userForm = fb.group({
      email: [null, Validators.compose([Validators.required, Validators.email])],
      lastName: [null, Validators.compose([Validators.required])],
      firstName: [null, Validators.compose([Validators.required])],
      groupUuid: [null, Validators.compose([Validators.required])],
      roleUuid: [null, Validators.compose([Validators.required])],
      passwordCreationMode: ['2', Validators.compose([Validators.required])],
      ldapName: ['', Validators.compose([Validators.required])],
      newPassword: ['', Validators.compose([Validators.required, Validators.maxLength(12), Validators.minLength(8)])],
      confirmPwd: ['', Validators.compose([Validators.required, Validators.maxLength(12), Validators.minLength(8)])]
    });
  }

  destroyModal(): void {
    this.modal.destroy({ data: 'this the result data' });
  }

  /**
   * 获取所属小组
   */
  getGroup() {
    this.groupService.getGroup()
      .subscribe((groupInfo) => {
        this.groupList = groupInfo;        // 数据集
        if (this.groupList) {
          this.userForm.controls.groupUuid.setValue(this.groupList[0].groupUuid);
        }
      });
  }

  /**
   * 获取角色
   */
  getRole() {
    this.groupService.getRole()
      .subscribe((roleGroup) => {
        this.roleGroup = roleGroup;        // 数据集
        if (this.roleGroup) {
          this.userForm.controls.roleUuid.setValue(this.roleGroup[0].roleUuid);
          console.log('=== getRole().this.roleGroup[0].roleUuid  ===>', this.roleGroup[0].roleUuid);
        }
      });
  }

  /**
   * 创建所属用户
   */
  saveUser() {
    if (this.userForm.controls.passwordCreationMode.value === '0') {
      this.userForm.removeControl('ldapName');
      console.log('提交', this.userForm.controls);
      // tslint:disable-next-line:forin
      for (const c in this.userForm.controls) {
        this.userForm.controls[c].markAsTouched();
      }
      if (this.userForm.valid) {
        this.info = {
          'activationType': this.userForm.controls.passwordCreationMode.value,
          'email': this.userForm.controls.email.value,
          'firstName': this.userForm.controls.firstName.value,
          'lastName': this.userForm.controls.lastName.value,
          'groupUuid': this.userForm.controls.groupUuid.value,
          'roleUuid': this.userForm.controls.roleUuid.value,
          'password': this.userForm.controls.newPassword.value,
          'passwordConfirm': this.userForm.controls.confirmPwd.value
        };
        this.addService(this.info);
      } else {
        this.nzMessageService.error('表单校验失败', { nzDuration: 10000 });
      }
    }
    if (this.userForm.controls.passwordCreationMode.value === '1') {
      this.userForm.removeControl('ldapName');
      this.userForm.removeControl('newPassword');
      this.userForm.removeControl('confirmPwd');

      console.log('提交', this.userForm.controls);
      // tslint:disable-next-line:forin
      for (const c in this.userForm.controls) {
        this.userForm.controls[c].markAsTouched();
      }
      if (this.userForm.valid) {
        this.info = {
          'activationType': this.userForm.controls.passwordCreationMode.value,
          'email': this.userForm.controls.email.value,
          'firstName': this.userForm.controls.firstName.value,
          'lastName': this.userForm.controls.lastName.value,
          'groupUuid': this.userForm.controls.groupUuid.value,
          'roleUuid': this.userForm.controls.roleUuid.value
        };
        this.addService(this.info);
      } else {
        this.nzMessageService.error('表单校验失败', { nzDuration: 10000 });
      }
    }
    if (this.userForm.controls.passwordCreationMode.value === '2') {
      this.userForm.removeControl('newPassword');
      this.userForm.removeControl('confirmPwd');
      console.log('提交', this.userForm.controls);
      // tslint:disable-next-line:forin
      for (const c in this.userForm.controls) {
        this.userForm.controls[c].markAsTouched();
      }
      if (this.userForm.valid) {
        this.info = {
          'activationType': this.userForm.controls.passwordCreationMode.value,
          'email': this.userForm.controls.email.value,
          'firstName': this.userForm.controls.firstName.value,
          'lastName': this.userForm.controls.lastName.value,
          'groupUuid': this.userForm.controls.groupUuid.value,
          'roleUuid': this.userForm.controls.roleUuid.value,
          'LDAPName': this.userForm.controls.ldapName.value
        };
        this.addService(this.info);
      } else {
        this.nzMessageService.error('表单校验失败', { nzDuration: 10000 });
      }

    }
  }

  private addService(info: any) {
    this.userService.saveCommonUser(this.info)
      .subscribe((userData) => {
        this.resultService(userData, '添加');
      });
  }

  private resultService(data: any, msg: string) {
    if (data.status) {
      this.nzMessageService.success(msg + '成功!', {
        nzDuration: 10000
      });
      this.modal.destroy();
    } else {
      this.nzMessageService.error(msg + '失败!请检查后重新填写', {
        nzDuration: 10000
      });
    }
  }


  /**
   * 判断邮箱是否重复
   */
  isEmailRepeat() {
    console.log('=== Janine.isEmailRepeat().email ===>', this.userForm.controls.email.value);
    if (this.userForm.controls.email.value) {
      this.userService.isEmailRepeat(this.userForm.controls.email.value)
        .subscribe((data) => {
          console.log(data);
          if (data.status === 3) { // 重复
            this.msgFlag = 'error';
          }
          if (data.status === 1) { // 可用
            this.msgFlag = 'success';
          }
        });
    }
  }

  pwdRepeate(): Boolean {
    const pwd = this.userForm.controls.newPassword.value;

    if (pwd === this.userForm.controls.confirmPwd.value) {
      return false;
    }
    return true;
  }

  ngOnInit() {
    this.getGroup();
    this.getRole();
  }

}
